<template>
  <div class="three-wrapper">
    <div class="box" ref="box"></div>
    <div class="actions">
      <button @click="startRoam">开始场景漫游</button>
      <button @click="stopRoam">停止漫游</button>
      <button @click="resetCamera">重置相机</button>
    </div>
  </div>
</template>

<script>
import TWEEN from '@tweenjs/tween.js'
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
const clock = new THREE.Clock()
const FPS = 30 // 设置渲染频率为30FBS，也就是每秒调用渲染器render方法大约30次
const renderT = 1 / FPS // 单位秒  间隔多长时间渲染渲染一次
let timeS = 0
export default {
  components: {},
  props: {},
  data() {
    return {
      el: null,
      scene: null,
      camera: null,
      renderer: null,
      controls: null,
      animationFrameId: null,
      isRoaming: false, // 是否正在漫游
      roamTween: null, // 漫游动画
      originalCameraPosition: new THREE.Vector3(), // 原始相机位置
      originalCameraTarget: new THREE.Vector3() // 原始相机目标
    }
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {
    this.el = this.$refs['box']
    this.clock = new THREE.Clock()

    this.initThree()
  },
  activated() {},
  deactivated() {},
  updated() {},
  beforeDestroy() {
    // 清理资源
    this.stopRoam()
    if (this.animationFrameId) {
      cancelAnimationFrame(this.animationFrameId)
    }
  },
  destroyed() {},
  methods: {
    initThree() {
      // 初始化 - 开始
      this.initScene() // 核心： 场景
      this.initCamera() // 核心: 相机
      this.initRender() // 核心 渲染器
      this.initLight()
      this.initControls()
      this.animate()
      this.scene.add(this.setGridHelper(100 * 2, 10 * 2))
      this.scene.add(this.setAxesHelper(100000))
      // 初始化 - 结束

      // 保存原始相机位置
      this.originalCameraPosition.copy(this.camera.position)
      this.originalCameraTarget.copy(this.controls.target)

      // 添加物体
      this.addMesh()
    },
    // 开始场景漫游
    startRoam() {
      if (this.isRoaming) return

      this.isRoaming = true
      console.log('开始场景漫游')

      // 禁用OrbitControls，让TWEEN完全控制相机
      this.controls.enabled = false

      // 定义漫游路径点
      const roamPath = [
        // 从当前位置开始
        {
          position: { x: 600, y: 600, z: 600 },
          target: { x: 0, y: 0, z: 0 }
        },
        // 俯视场景
        {
          position: { x: 0, y: 400, z: 0 },
          target: { x: 0, y: 0, z: 0 }
        },
        // 从侧面观看
        {
          position: { x: -300, y: 200, z: 300 },
          target: { x: 0, y: 50, z: 0 }
        },
        // 近距离观看
        {
          position: { x: 50, y: 80, z: 150 },
          target: { x: 0, y: 30, z: 0 }
        },
        // 从另一个角度
        {
          position: { x: 200, y: 150, z: -200 },
          target: { x: 0, y: 20, z: 0 }
        },
        // 回到起始位置
        {
          position: { x: 300, y: 300, z: 300 },
          target: { x: 0, y: 0, z: 0 }
        }
      ]

      this.startRoamPath(roamPath, 0)
    },
    // 执行漫游路径
    startRoamPath(path, index) {
      if (!this.isRoaming || index >= path.length) {
        this.completeRoam()
        return
      }

      const currentPoint = path[index]
      const nextIndex = (index + 1) % path.length
      const isLastPoint = index === path.length - 1

      const duration = 1000

      // 停止之前的动画
      if (this.roamTween) {
        this.roamTween.stop()
      }

      // 创建相机位置动画
      const positionTween = new TWEEN.Tween(this.camera.position)
        .to(currentPoint.position, duration)
        .easing(TWEEN.Easing.Quadratic.InOut)

      // 创建相机目标点动画
      const targetTween = new TWEEN.Tween(this.controls.target)
        .to(currentPoint.target, duration)
        .easing(TWEEN.Easing.Quadratic.InOut)

      // 同时执行位置和目标点动画
      positionTween.chain(
        new TWEEN.Tween({})
          .delay(1000) // 在每个点停留1秒
          .onComplete(() => {
            if (isLastPoint) {
              // 如果是最后一个点，循环播放
              this.startRoamPath(path, 0)
            } else {
              this.startRoamPath(path, nextIndex)
            }
          })
      )

      positionTween.start()
      targetTween.start()

      this.roamTween = positionTween
    },
    // 停止漫游
    stopRoam() {
      this.isRoaming = false
      if (this.roamTween) {
        this.roamTween.stop()
        this.roamTween = null
      }
      // 重新启用OrbitControls
      this.controls.enabled = true
      console.log('停止场景漫游')
    },
    // 重置相机
    resetCamera() {
      this.stopRoam()

      // 平滑回到原始位置
      new TWEEN.Tween(this.camera.position)
        .to(this.originalCameraPosition, 1500)
        .easing(TWEEN.Easing.Quadratic.InOut)
        .start()

      new TWEEN.Tween(this.controls.target)
        .to(this.originalCameraTarget, 1500)
        .easing(TWEEN.Easing.Quadratic.InOut)
        .start()
    },
    // 漫游完成
    completeRoam() {
      console.log('场景漫游完成')
      this.stopRoam()
    },
    addMesh() {
      const geometry = new THREE.BoxGeometry(10, 10, 10)
      const material = new THREE.MeshLambertMaterial({
        color: new THREE.Color('#00ff00'),
        transparent: true
      })
      const mesh = new THREE.Mesh(geometry, material)
      this.scene.add(mesh)
    },
    setGridHelper(size, divisions) {
      return new THREE.GridHelper(size, divisions)
    },
    setAxesHelper(size) {
      return new THREE.AxesHelper(size)
    },
    // 初始化场景
    initScene() {
      this.scene = new THREE.Scene()
    },
    // 初始化相机
    initCamera() {
      const asp = this.el.offsetWidth / this.el.offsetHeight
      this.camera = new THREE.PerspectiveCamera(45, asp, 0.1, 10000000)
      this.camera.position.set(300, 300, 300)
      this.camera.lookAt(this.scene.position)
      this.scene.add(this.camera)
    },
    initRender(clearColor = '#000') {
      const width = this.el.offsetWidth
      const height = this.el.offsetHeight
      this.renderer = new THREE.WebGLRenderer({
        antialias: true,
        alpha: true
      })
      this.renderer.setPixelRatio(window.devicePixelRatio)
      this.renderer.setSize(width, height)
      this.el.append(this.renderer.domElement)
      // this.renderer.setClearColor(clearColor, 1) // 不设置背景色
    },
    initLight() {
      const ambientLight = new THREE.AmbientLight('#fff', 0.3)
      this.scene.add(ambientLight)
      const directionalLight = new THREE.DirectionalLight('#fff', 0.8)
      directionalLight.position.set(30, 30, 30).normalize()
      this.scene.add(directionalLight)
    },
    initControls() {
      this.controls = new OrbitControls(
        this.camera,
        this.renderer.domElement,
        {}
      )
      this.controls.enableDamping = true
      this.controls.dampingFactor = 0.05
    },
    render() {
      const dt = this.clock.getDelta()
      const T = clock.getDelta()
      timeS = timeS + T
      if (timeS > renderT) {
        TWEEN.update() // note: 这个代码不能少 否则动画不会动

        // 如果正在漫游，需要手动更新相机lookAt
        if (this.isRoaming) {
          this.camera.lookAt(this.controls.target)
        }

        this.controls.update(dt)
        this.renderer.render(this.scene, this.camera)
      }
    },
    animate() {
      this.render()
      this.animationFrameId = requestAnimationFrame(this.animate)
    }
  },
  filters: {}
}
</script>
<style scoped lang="scss">
.three-wrapper {
  height: 100%;
  position: relative;
  .box {
    height: 100%;
    width: 100%;
    background: url(./images/map-bg.png);
    background-size: cover;
    background-repeat: no-repeat;
    overflow: hidden;
  }
  .actions {
    position: absolute;
    bottom: 10px;
    left: 10px;
    display: flex;
    gap: 10px;

    button {
      padding: 8px 16px;
      border: none;
      background-color: #409eff;
      color: #fff;
      border-radius: 6px;
      cursor: pointer;
      font-size: 14px;
      transition: all 0.3s ease;

      &:hover {
        background-color: #66b1ff;
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
      }

      &:nth-child(2) {
        background-color: #e6a23c;
        &:hover {
          background-color: #ebb563;
        }
      }

      &:nth-child(3) {
        background-color: #f56c6c;
        &:hover {
          background-color: #f78989;
        }
      }
    }
  }
}
</style>
